package com.gitee.cirnochat.chat.filter;

import com.gitee.cirnochat.websocket.model.dto.WebSocketUserMessage;
import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.security.Principal;
import java.util.List;

/**
 * 消息过滤器链
 * 用于管理和执行一系列消息过滤器
 * @author FlanChan
 * @since 2025/6/28 14:22
 */
@Component
@RequiredArgsConstructor
public class MessageFilterChain {
    private final List<MessageFilter> filters;
    private MessageFilter head;

    @PostConstruct
    public void init() {
        if (filters.isEmpty()) return;
        // 按照 Order 注解的值进行排序，值小的在前面
        filters.sort((a, b) -> {
            Order orderA = a.getClass().getAnnotation(Order.class);
            Order orderB = b.getClass().getAnnotation(Order.class);
            int valueA = orderA != null ? orderA.value() : Integer.MAX_VALUE;
            int valueB = orderB != null ? orderB.value() : Integer.MAX_VALUE;
            return Integer.compare(valueA, valueB);
        });
        // 构建过滤器链
        head = filters.getFirst();
        MessageFilter current = head;
        for (int i = 1; i < filters.size(); i++) {
            current.setNext(filters.get(i));
            current = filters.get(i);
        }
    }

    /**
     * 执行过滤器链
     * @param message 要过滤的消息
     */
    public void doFilter(WebSocketUserMessage message, Principal principal) {
        if (head != null) {
            head.doFilter(message,principal);
        }
    }
}